package com.tamir.template.express.parse;

import com.tamir.template.bean.LogicOperate;
import com.tamir.template.bean.TNode;
import com.tamir.template.config.OperatorConfig;
import com.tamir.template.config.TemplateNodeTypeConfig;
import com.tamir.template.util.LogicOperateUtil;
import com.tamir.template.util.StringUtil;

/**
 * @author : tanggh
 * @description :〈描述〉
 * @date : 2017/1/4
 */
public class LogicOperateHandleParser extends AbstractLogicHandleParse
{

    /**
     * 设置node的输入输出关键字和对应的值
     *
     * @param node
     */
    public void parseIOKeyForNode(TNode node)
    {
        if(node != null && (node.gettLogicType().gettLogicType().equalsIgnoreCase
                (TemplateNodeTypeConfig.NODE_TYPE_OPERATOR))){
            String keyAndValue = node.getRealExpress().replaceAll("\\s+", " ");
            String[] ex = keyAndValue.split("\\s");
            //如果ex[0]是注册的表达式 如:if,则用“”替换if,再做为逻辑解析表达式
            if(TemplateNodeTypeConfig.getInstance().getRegisterLogicHandleParse().get(ex[0]) != null){
                keyAndValue = keyAndValue.replaceAll("\\s+", "").replaceAll(ex[0], "");
            }
            LogicOperate rootLogicOperate = OperatorConfig.getInstance().getOperatorParser()
                    .parseExpress(keyAndValue);
            //设置逻辑操作符对象
            node.setLogicOperate(rootLogicOperate);
//            rootLogicOperate.setParentNode(node);
            //解析inputKey
            parseIOkeyForLogicOperate(rootLogicOperate);
        }
    }

    /**
     * 解析逻辑操作对象的inputKey
     * @param operate
     */
    public void parseIOkeyForLogicOperate(LogicOperate operate){
        if(operate != null){
            //操作符为null则认为是表达式, 有操作符则认为是逻辑操作结点
            if (StringUtil.isNotEmpty(operate.getOperator())){
                parseIOkeyForLogicOperate(operate.getLeftOperate());
                parseIOkeyForLogicOperate(operate.getRightOperate());
            }
            else{
                operate.setInputKey(LogicOperateUtil.getInputKey(operate.getExpress()));
            }
        }
    }

    public static void main(String[] args)
    {

    }
}
